<template>
  <div class="login-page">
    <!-- 登录页面 -->
     <!-- 导航栏 -->
     <van-nav-bar title="登录页"/>
     <!-- 登录表单 -->
     <van-form @submit="onSubmit">
      <!--
      输入框组件
      name提交给后端时的键
      rules验证规则：
      required:是否必填
      message:错误提示信息
      pattern:正则表达式
       -->
  <van-field
    v-model="username"
    name="username"
    label="用户名"
    placeholder="请输入用户名"
    :rules="[
      { required: true, message: '请填写用户名' },
      { pattern: /^[a-zA-Z0-9]{3,10}$/, message: '用户名格式不正确' }
      ]"
  />
  <van-field
    v-model="password"
    type="password"
    name="password"
    label="密码"
    placeholder="请输入密码"
    :rules="[
      { required: true, message: '请填写密码' },
      { pattern: /^[a-zA-Z0-9]{3,10}$/, message: '密码格式不正确' }
      ]"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit">提交</van-button>
  </div>
      </van-form>
    <router-link to="/register" class="link">没有账号？去注册</router-link>
  </div>
</template>

<script>
import { loginApi } from '@/api/user'
import { setToken } from '@/utils/storage'

export default {
  name: 'LoginPage',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit (values) {
      console.log('submit', values)
      const res = await loginApi(values)
      console.log(res)
      if (res.code === 10000) {
        this.$toast.success('登录成功')
        // localStorage.setItem('interview_h5_token', res.data.token)
        setToken(res.data.token)
        this.$router.push('/')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
  display: inline-block;
  width: 100%;
  text-align: right;
  // 解决内边距会撑大盒子
  box-sizing: border-box;
}
</style>
